import { Injectable } from '@nestjs/common';
import { PostRepository } from '../entity/EntityConfig/post.repoistory';
import { paginate } from '../database/helpers'
import { PaginateOptions, PostCreateType, PostUpdateType } from 'src/entity/EntityConfig/types';
import { EntityNotFoundError } from 'typeorm';
import { PostEntity } from '../entity/Entity/post.entity';
import {omit } from 'lodash';
import { CategoryRepository } from 'src/entity/repositories';
import { CategoryService } from './Category.Service';
import { SearchService } from './search.service';
import { SearchType } from 'src/config/defaultconfig';

@Injectable()
export class PostService {
    constructor(
        protected repository: PostRepository,
        protected categoryRepository: CategoryRepository,
        protected categoryService: CategoryService,
        protected searchService?: SearchService,
        protected search_type: SearchType = 'against',

    ) { }

    //查询文章详情
    async detail(id: string) {

        let item = await this.repository.buildBaseQB().where(`post.id=:id`, { id }).getOne()
        if (!item) {
            throw new EntityNotFoundError(PostEntity, 'id is not exists !')

        }
        return item
    }
    //获取总数数据
    async paginate(options: PaginateOptions) {
        let qb = await this.repository.buildBaseQB()
        return paginate(qb, options)
    }

    //创建文章
    async create(data: PostCreateType) {
        let item = await this.repository.save(data)
        //  console.log(item);

        return this.detail(item.id)
    }
    //更新文章
    async updated(data: PostUpdateType) {

        let id = data.id
      
        let item =await this.repository.update(id, omit(data, ['id']));
        return this.detail(id)
    }

    //删除文章

    async delete(id: string) {
        const item = await this.repository.findOneByOrFail({ id });
        return this.repository.remove(item);
    }
}